package com.xingchi.tornado.security.config;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.xingchi.tornado.core.config.LocalDateTimeSerializerModule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
import org.springframework.session.web.http.DefaultCookieSerializer;
import org.springframework.session.web.http.HttpSessionIdResolver;

@Configuration
public class SessionConfig {

    @Autowired
    private SecurityProperties properties;

    @Bean
    public RedisSerializer<Object> springSessionDefaultRedisSerializer() {
        Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
        ObjectMapper objectMapper = builder.modules(new LocalDateTimeSerializerModule())
                .createXmlMapper(false)
                .build();
        SimpleModule module = new SimpleModule();
        module.setMixInAnnotation(SimpleGrantedAuthority.class, SimpleGrantedAuthorityMixIn.class);
        objectMapper.registerModule(module);
        objectMapper.activateDefaultTyping(objectMapper.getPolymorphicTypeValidator(), ObjectMapper.DefaultTyping.NON_FINAL);
        return new GenericJackson2JsonRedisSerializer(objectMapper);
    }

    abstract static class SimpleGrantedAuthorityMixIn {
        @JsonCreator
        public SimpleGrantedAuthorityMixIn(@JsonProperty("authority") String role) {
        }
    }

    @Bean
    @Primary
    public HttpSessionIdResolver sessionIdResolver() {
        DefaultCookieSerializer defaultCookieSerializer = new DefaultCookieSerializer();
        defaultCookieSerializer.setCookieName("SESSION_ID");
        defaultCookieSerializer.setCookiePath("/");
        defaultCookieSerializer.setCookieMaxAge(properties.getExpiresIn());
        defaultCookieSerializer.setSameSite("Lax");
        return new CompositeSessionIdResolver(defaultCookieSerializer);
    }
}
